{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Ever Given\n",
    "\n",
    "<img align=\"right\" src=\"https://anitagraser.github.io/movingpandas/assets/img/movingpandas.png\">\n",
    "\n",
    "This notebook presents an analysis of the vessel situation following the grounding of Ever Given in the Suez Canal.\n",
    "\n",
    "\n",
    "The dataset used covers the time span between 2021-03-20 00:00 and 2021-03-24 12:52 UTC.\n",
    " \n",
    "This data has generously been provided by VesselsValue.\n",
    "\n",
    "\n",
    "<img align=\"left\" src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Container_Ship_%27Ever_Given%27_stuck_in_the_Suez_Canal%2C_Egypt_-_March_24th%2C_2021_cropped.jpg/320px-Container_Ship_%27Ever_Given%27_stuck_in_the_Suez_Canal%2C_Egypt_-_March_24th%2C_2021_cropped.jpg\">\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from IPython.core.display import display, HTML\n",
    "display(HTML(\"<style>.container { width:100% !important; }</style>\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import geopandas as gpd\n",
    "import movingpandas as mpd\n",
    "from geopandas import GeoDataFrame, read_file\n",
    "from shapely.geometry import Point, LineString, Polygon\n",
    "from datetime import datetime, timedelta\n",
    "\n",
    "from holoviews import opts, dim\n",
    "from holoviews.selection import link_selections\n",
    "\n",
    "import warnings\n",
    "warnings.simplefilter(\"ignore\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "EVERID = 235\n",
    "FSIZE = 500"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv('E:/Geodata/VesselsValue/boat-positions.csv')\n",
    "df['t'] = pd.to_datetime(df['ais_pos_timestamp'], format='%d/%m/%Y %H:%M')\n",
    "df = df.set_index('t').tz_localize(None)\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gdf = gpd.GeoDataFrame(df.drop(['longitude', 'latitude', 'ais_pos_timestamp'], axis=1), \n",
    "                       crs='epsg:4326', geometry=[Point(xy) for xy in zip(df.longitude, df.latitude)])\n",
    "gdf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gdf.hvplot(geo=True, tiles='OSM', frame_width=FSIZE, frame_height=FSIZE)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "trajs = mpd.TrajectoryCollection(gdf, 'ID')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "evergiven = trajs.get_trajectory(EVERID)\n",
    "evergiven.hvplot(line_width=7, frame_width=FSIZE, frame_height=FSIZE)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "stop_pts = mpd.TrajectoryStopDetector(trajs).get_stop_points(min_duration=timedelta(hours=3), max_diameter=1000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "stop_pts['ID'] = stop_pts.index\n",
    "stop_pts['ID'] = stop_pts['ID'].apply(lambda row: int(row.split('_')[0]))\n",
    "stop_pts['duration_h'] = (stop_pts['end_time']-stop_pts['start_time']).dt.total_seconds() / 3600\n",
    "stop_pts"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Ever Given ran aground around 7:40 local time (5:40 UTC) on 23rd March 2021"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "stop_pts[stop_pts['ID']==EVERID]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot = evergiven.hvplot(line_width=5, color='red', frame_width=FSIZE, frame_height=FSIZE, alpha=0.5)\n",
    "plot = plot * stop_pts.hvplot(geo=True, hover_cols=['start_time'], size=20) \n",
    "plot = plot * stop_pts[stop_pts['ID']==EVERID].hvplot(geo=True, hover_cols=['start_time'], size=dim('duration_h')/2, color='red', \n",
    "                                                      title='Trajectory & stop location of Ever Given and stops of other vessels')\n",
    "plot2 = pd.DataFrame(stop_pts).hvplot.scatter(title='Stop start & duration (in hours)', x='start_time', y='duration_h', frame_width=FSIZE, frame_height=FSIZE) \n",
    "plot2 = plot2 * pd.DataFrame(stop_pts[stop_pts['ID']==EVERID]).hvplot.scatter(x='start_time', y='duration_h', color='red', size=200)\n",
    "link_selections(plot + plot2)#.cols(1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*Data generously provided by VesselsValue.*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from datashader.utils import lnglat_to_meters\n",
    "from holoviews.element import tiles\n",
    "\n",
    "df = stop_pts.copy()\n",
    "df['lon'] = df.geometry.x\n",
    "df['lat'] = df.geometry.y\n",
    "df = pd.DataFrame(df)\n",
    "df.loc[:, 'x'], df.loc[:, 'y'] = lnglat_to_meters(df.lon, df.lat)\n",
    "\n",
    "plot = tiles.OSM() * df.hvplot.scatter(x='x', y='y', frame_width=FSIZE, frame_height=FSIZE, title='Trajectory & stop location of Ever Given and stops of other vessels')\n",
    "plot2 = df.hvplot.scatter(title='Stop start & duration (in hours)', x='start_time', y='duration_h', frame_width=FSIZE, frame_height=FSIZE)\n",
    "\n",
    "link_selections(plot + plot2)#.cols(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
